package wxapp

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
)

type WxApiRet struct {
	ErrCode 		int64  		`json:"errcode"`
	ErrMsg  		string 		`json:"errmsg"`
}

func WxApiGet(wx_addr string) ([]byte, error) {
	res, err := http.Get(wx_addr)
	if err != nil {
		return nil, err
	}

	raw, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return nil, err
	}

	if res.StatusCode != http.StatusOK {
		return nil, errors.New(fmt.Sprintf("http statusCode=%v", res.StatusCode))
	}

	return raw, nil
}

func WxApiPost(wx_addr string, data []byte) ([]byte, error) {
	res, err := http.Post(wx_addr, "application/json; charset=utf-8", bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}

	raw, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return nil, err
	}

	if res.StatusCode != http.StatusOK {
		return nil, errors.New(fmt.Sprintf("http statusCode=%v", res.StatusCode))
	}

	return raw, nil
}

func WxApiPostStruct(wx_addr string, param interface{}) ([]byte, error) {
	data, err := json.Marshal(param)
	if err != nil {
		return nil, err
	}
	return WxApiPost(wx_addr, data)
}

//使用multipart/form-data发送文件
func PostFileByFormData(url string, params map[string]string, file_path string, file_key string) (string, error) {
	file, err := os.Open(file_path)
	defer file.Close()
	if err != nil {
		return "", err
	}
	defer file.Close()

	bodyBuf := &bytes.Buffer{}
	bodyWrite := multipart.NewWriter(bodyBuf)
	for key, val := range params {
		_ = bodyWrite.WriteField(key, val)
	}

	fileWrite, err := bodyWrite.CreateFormFile(file_key, file.Name())
	_, err = io.Copy(fileWrite, file)
	if err != nil {
		return "", err
	}
	bodyWrite.Close()

	client := http.Client{}
	req, err := http.NewRequest(http.MethodPost, url, bodyBuf)
	if err != nil {
		return "", err
	}

	req.Header.Set("Content-Type", bodyWrite.FormDataContentType())
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != 200 {
		err := fmt.Errorf("status:%d", resp.StatusCode)
		return string(result),err
	}
	return string(result), nil
}



